# -*- coding: UTF-8 -*-

import socketserver
import socket
import os
from msg.order import Order
from common.tools import Tool
from msg.protocol import Protocol
from common.conf import conf
from msg.action import Action

t = Tool()
c = conf
p = Protocol()
a = Action()
exp = 1800

# http://39.106.152.15/deploy/static/gb/000000C9/live/index.m3u8
class MyUdp(socketserver.ThreadingUDPServer):
    def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)


class MyHandler(socketserver.BaseRequestHandler):

    def handle(self):
        cam_ip, cam_port = self.client_address
        data = self.request[0]
        str_receive = data.decode('gbk')
        if len(str_receive) < 10: return
        cseq = t.line_by_word(str_receive, "CSeq:")
        print(f"*******{cseq}**********{cam_ip}")
        # print(str_receive)
        if c.ty_register in cseq:
            back = p.register_ok(str_receive)
            self.request[1].sendto(back.encode(), self.client_address)
        elif c.ty_msg in cseq:
            back = p.register_ok(str_receive)
            self.request[1].sendto(back.encode(), self.client_address)
            cam_id = str_receive[(str_receive.find('From:') + 11):str_receive.find('@', str_receive.find('From:'))]
            # print ("str recv msg==",str_receive)
            # for nvr cam_id is nvr id,no chan id in msg 存储的是nvr,用的是他的第一行IP,port等,没有通道信息
            a.save_msg(cam_id, str_receive, cam_ip, cam_port)

        elif c.ty_invite in cseq:
            if "SIP/2.0 200 OK" in str_receive:
                back = p.ack_invite(str_receive)
                print ("recv==",str_receive)
                print ("invite ack==",back,back.encode())
                self.request[1].sendto(back.encode(), self.client_address)
                # base on call id save ack and to tag
                a.on_invite_ack(str_receive)
            elif "SIP/2.0 400 Bad Request" in str_receive:
                cam_id = str_receive[(str_receive.find('To:') + 9):str_receive.find('@', str_receive.find('To:'))]
                print("bad reqeust", cam_id)

        elif c.ty_bye in cseq:
            back = p.bye(str_receive)
            # bye的时候,首先同意,否则设备会不停的发
            print ("*****************say bye*************")
            self.request[1].sendto(back.encode(), self.client_address)
        elif "WQ ORDER" in cseq:
            cid,chan=Order().extract(str_receive)
            print("order invite====",cid,chan)
            Order().invite_local(cid,chan)
        elif "WQ STOP" in cseq:
            cid,chan=Order().extract(str_receive)
            print("order bye====",cid,chan)
            Order().bye_local(cid,chan)




if __name__ == '__main__':
    print(c.sip_ip, c.sip_port)
    # win ifconfig,   linux 0.0.0.0
    local = c.sip_ip if os.name == "nt" else "0.0.0.0"
    s = MyUdp((local, c.sip_port), MyHandler)
    s.serve_forever()
